Are there any tools available to track the creation and lifetime of Java threads? I would be interested in all of the following:
- The call stack which called new Thread()
- The call stack which called start()
- The lifetime of the run() method
Are there any tools available to track the creation and lifetime of Java threads? I would be interested in all of the following:
I have written and published an open source tool to answer this question.
I have blogged about the tool here.
I don't know of any framework like this. You certainly could subclass the Thread class and store this information on your own like the following. This however will not track Threads that are allocated in other classes such as Executors, etc..
public class MyThread extends Thread { StackTraceElement[] constructorTrace; StackTraceElement[] startTrace; long runStartTimeMillis; long runFinishTimeMillis; // you'll need to duplicate the constructors you need public MyThread() { super(); constructorTrace = Thread.currentThread().getStacktrace(); } @Override public void start() { super.start(); startTrace = Thread.currentThread().getStacktrace(); } @Override public void run() { runStartTimeMillis = System.currentTimeMillis(); super.run(); runFinishTimeMillis = System.currentTimeMillis(); } } Thread.currentThread().getStacktrace() and System.nanoTime() for timing. You can also just store the new Throwable and only take the StackTrace if you need it.Thread.getStacktrace(). I forgot about that. The stacktrace is filled in the Throwable constructor so I don't think that saves anything.getStackTraceElement I guess translates the native structures into Java StackTraceElement. Makes sense. Thanks.